package com.xszx.ucenter.controller;


import com.xszx.commonutils.JwtUtils;
import com.xszx.commonutils.R;
import com.xszx.servicebase.exceptionhandler.QinXueException;
import com.xszx.ucenter.entity.Member;
import com.xszx.ucenter.entity.dto.LoginDto;
import com.xszx.ucenter.entity.dto.RegisterDto;
import com.xszx.ucenter.service.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author 白熊
 * @since 2024-07-24
 */
@RestController
@RequestMapping("/ucenter/member")
//@CrossOrigin
@Api(tags = "注册登录功能")
public class MemberController {

    @Autowired
    private MemberService memberService;


    @GetMapping("countregister/{day}")
    @ApiOperation("统计某一天的注册人数")
    public R registerCount(@PathVariable("day") String day){
        Integer countRegisterByDay = memberService.countRegisterByDay(day);
        return R.ok().data("countRegister",countRegisterByDay);
    }

    @PostMapping("getInfoUc/{id}")//通过id获取用户信息
    public R getInfo(@PathVariable("id") String id) {
        //根据用户id获取用户信息
        Member member = memberService.getById(id);
        return R.ok().data("item", member);
    }

    @PostMapping("register")
    @ApiOperation("注册")
    public R register(@ApiParam(name = "registerDto",value = "会员对象")
            @RequestBody RegisterDto registerDto){
        memberService.register(registerDto);
        return  R.ok().message("注册成功");
    }

    @PostMapping("login")
    @ApiOperation("登录")
    public R login(@ApiParam(name = "loginDto",value = "会员对象")
                       @RequestBody LoginDto loginDto){
        String token = memberService.login(loginDto);//登录时会传给后端一个token令牌用,缓存起来
        return R.ok().data("token",token);
    }

    @ApiOperation("根据token获取登录信息")
    @GetMapping("getLoginInfo")
    public R getLoginInfo(HttpServletRequest request) {
        try {
            //JWT就是授权给第三方可以登录注册
            String memberId = JwtUtils.getMemberIdByJwtToken(request);
            Member member = memberService.getLoginInfo(memberId);
            return R.ok().data("item", member);
        } catch (Exception e) {
            e.printStackTrace();
            throw new QinXueException(20001, "error");
        }
    }
}

